package com.example.edu.app;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings.Secure;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.edu.connection.connection;
public class Login extends FragmentActivity implements OnClickListener {
	final Context context=this;
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 
		 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		 StrictMode.setThreadPolicy(policy); 
		 
		 String android_id = Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID); 
		 
		 Log.d("Device Id", android_id);
		 
		 setContentView(R.layout.login);
		 
		 Button b=(Button)findViewById(R.id.btn_login);
		 b.setOnClickListener(this);
		 
		 if(connection.isUserConnectedBefore(android_id))
			 goToMainScreen(findViewById(R.id.login));
		 
	 }
	 
	 public void onClick(View v){
		 	 
		 EditText password= (EditText)findViewById(R.id.login_text_password);
		 EditText email= (EditText)findViewById(R.id.login_email);
		 String android_id = Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID); 
		 if(connection.loginToEdunera(email.getText().toString(), password.getText().toString(), android_id))
		 {
			 
			 goToMainScreen(v);
		 }else
		 {
			 
			 showAlert("Login","Login is unsuccessfull, please try again",true);
		 }
		 
	 }
	 
	 private void goToMainScreen(View v){
		 Intent i=new Intent(v.getContext(),CourseListActivity.class);
		 startActivity(i);
	 }
	
	 private void showAlert(String title, String message,boolean hasButtons){
		 AlertDialog.Builder alert = new AlertDialog.Builder(context);
         alert.setTitle(title); //Set Alert dialog title here
         alert.setMessage(message); //Message here
         if(hasButtons){
	         alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int whichButton) {
	             dialog.cancel();
	
	           }
	         });
         }
         AlertDialog alertDialog = alert.create();
         alertDialog.show();
	 }
	
}
